<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\GoodsCategory;
use App\Models\Goods;
use App\Models\SpecGoodsPrice;
use App\Models\Spec;
use DB;
class IndexController extends Controller
{
    /*
	 * 获取一级分类
	 * */
    public function getmenu(){
    	$cat = GoodsCategory::where('pid',0)->select('id','name','image')->orderBy('sort')->get();
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> $cat
			]);
    }
	/*
	 * 
	 * 获取二级分类
	 * */
	protected function getmenu2(Request $request){
		$pid = $request->input('pid');
		$menu_name = GoodsCategory::find($pid)['name'];
		$cat = GoodsCategory::where('pid',$pid)->select('id','name','image')->get();
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> array(
				'menu_name' => $menu_name,
				'list'	=> $cat
				)
			]);
	}
	
	
	
	
	/*
	 * 获取商品列表,或当前分类下商品
	 * */
	public function goodslist(Request $request){
		$cat_id = $request->input('cat_id');
		$status = $request->input('status');
		$goods = Goods::select('goods_id','goods_name','original_img','shop_price')
			->when($cat_id,function ($query) use ($cat_id){
				return $query->where('cat_id',$cat_id);
			})
			->when($status,function($query) use ($status){
				switch ($status) {
					case 1:
						return $query->orderBy('sales_sum','desc');
						break;
					case 2:
						return $query->orderBy('on_time','desc');
						break;
					case 3:
						return $query->orderBy('shop_price');
						break;											
				}
				
			})
			->get();
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> $goods
			]);
	}
	
	
	/*
	 * 
	 * 商品详情
	 * */
	public function goodsDetails(Request $request){
		$goods_id = $request->input('goods_id');
		$goods = Goods::find($goods_id);
		$goodsSpecPrice = $goods->getspec()->select('id','goods_id','key','key_name','price','store_count')->get(); 
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> array(
				'goods'	=> $goods,
				'goodsSpecPrice' =>$goodsSpecPrice,
				'spec'	=> $this->get_spec($goods_id)
				)
			]);		
	}
	
	/*
	 * 获取商品规格
	 * 
	 * */
	private function get_spec($goods_id){
		$keys = SpecGoodsPrice::where('goods_id',$goods_id)->select(DB::raw("GROUP_CONCAT(`key` SEPARATOR '_') abc"))->first()['abc'];
		$filter_spec = array();
		if($keys){
			$keys = explode('_', $keys);

			$filter_spec2 = Spec::join('spec_item','spec_item.spec_id','spec.id')
				->whereIn('spec_item.id',$keys)->select('spec.name','spec_item.item','spec_item.id as item_id')->get();
            foreach ($filter_spec2 as $key => $val) {
                $filter_spec[$val->name][] = array(
                    'item_id' => $val->item_id,
                    'item' => $val->item,
                    'action' => FALSE
                );
            }
			return $filter_spec;
		}
	}
}
